package com.example.seckill.domain.model;

import com.example.seckill.domain.share.DddEntity;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author Martin
 */
@Slf4j
@Getter
@Setter
@ToString
@RequiredArgsConstructor
@Entity
public class Seckill implements DddEntity<Seckill> {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private Long productId;
    private BigDecimal seckillPrice;
    private LocalDateTime startTime;
    private LocalDateTime endTime;
    private Integer seckillStockQuantity;

    public Seckill(Long id, Long productId, BigDecimal seckillPrice, LocalDateTime startTime, LocalDateTime endTime, Integer seckillStockQuantity) {
        this.id = id;
        this.productId = productId;
        this.seckillPrice = seckillPrice;
        this.startTime = startTime;
        this.endTime = endTime;
        this.seckillStockQuantity = seckillStockQuantity;
    }

    // getters and setters
    // ...

    public boolean isAvailable() {
        return LocalDateTime.now().isAfter(startTime) && LocalDateTime.now().isBefore(endTime);
    }

    public void reduceSeckillStockQuantity(Integer quantity) {
        if (quantity > seckillStockQuantity) {
            throw new IllegalArgumentException("Seckill stock quantity is not enough.");
        }
        seckillStockQuantity -= quantity;
    }

    @Override
    public boolean sameIdentityAs(Seckill other) {
        return other != null && other.getId().equals(this.id);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) {
            return false;
        }
        Seckill seckill = (Seckill) o;
        return id != null && Objects.equals(id, seckill.id);
    }

    @Override
    public int hashCode() {
        return getClass().hashCode();
    }
}

